/****************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.     *
 *                                                              *
 * Copyright (C) 2009, Jun Li All rights reserved.              *
 * More about Jun{                                              *
 * Homepage: http://www.jpxx.org/                               *
 * Email   : lijun@jpxx.org                                     *
 * }                                                            *
 * SOFTWARE ENGINEERING COLLEGE OF SICHUAN UNIVERSITY           *
 *                                                              *
 ****************************************************************/
package org.jpxx.sec.common.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * 
 * @author Jun Li lijun@jpxx.org (http://www.jpxx.org)
 * @version 1.0.0 $ org.jpxx.sec.common.util.FileToolkit.java $ $ Date:
 *          2009-5-10 $
 */
public class FileToolkit {

	private static Logger log = Logger.getLogger(FileToolkit.class);

	public static void copyFile(String srcFile, String destDir)
			throws IOException {
		File f = new File(srcFile);
		if (!f.exists()) {
			log.warn(f.getAbsolutePath() + " not exist.");
			return;
		}
		FileUtils.copyFileToDirectory(f, new File(destDir));
	}

	public static void delete(String file) throws IOException {
		File f = new File(file);
		if (f.isDirectory()) {
			FileUtils.deleteDirectory(f);
		} else {
			f.delete();
		}

	}

	public static void copy(String resDir, String destDir) throws IOException {

		File dir = new File(resDir);
		File resFiles[] = dir.listFiles();
		for (int i = 0; i < resFiles.length; i++) {
			File f = resFiles[i];
			if (f.isFile()) {
				copyFile(f.getAbsolutePath(), destDir);
			} else {
				String destF = destDir + File.separator + f.getName();
				if (f.getName().startsWith(".")) {
					continue;
				}

				File temp = new File(destF);
				if (!temp.exists()) {
					temp.mkdirs();
				}
				copy(f.getAbsolutePath(), destF);
			}
		}
	}

	/**
	 * 
	 * @param resDir
	 *            压缩文件目录
	 * @param zipFile
	 *            压缩文件的保存路径
	 */
	public static void createZipFile(String resDir, String zipFile)
			throws IOException {
		list = new ArrayList<String>();

		resDir = resDir.replace('\\', '/');
		zipFile = zipFile.replace('\\', '/');
		File dir = new File(zipFile).getParentFile();
		if (dir != null && !dir.exists()) {
			dir.mkdirs();
		}

		byte b[] = new byte[512];

		List<String> fileList = listAllFile(resDir);

		File f = new File(zipFile);
		FileOutputStream fileOutputStream = new FileOutputStream(f);
		// 使用输出流检查
		CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream,
				new CRC32());
		// 声明输出zip流
		ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(cs));

		for (int i = 0; i < fileList.size(); i++) {
			InputStream in = new FileInputStream(fileList.get(i));
			String fileName = fileList.get(i);
			fileName = fileName.replace(resDir, "");
			ZipEntry e = new ZipEntry(fileName);
			out.putNextEntry(e);
			int len = 0;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
			out.closeEntry();
		}
		out.close();

	}

	/**
	 * 
	 * @param resDir
	 *            classes文件目录
	 * @param jarFile
	 *            Jar文件的保存路径
	 */
	public static void createJarFile(String resDir, String jarFile)
			throws IOException {
		list = new ArrayList<String>();

		resDir = resDir.replace('\\', '/');
		jarFile = jarFile.replace('\\', '/');
		File dir = new File(jarFile).getParentFile();
		if (dir != null && !dir.exists()) {
			dir.mkdirs();
		}

		byte b[] = new byte[512];

		List<String> fileList = listAllFile(resDir);

		File f = new File(jarFile);
		FileOutputStream fileOutputStream = new FileOutputStream(f);
		// 使用输出流检查
		CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream,
				new CRC32());

		Manifest man = new Manifest();
		man.read(new FileInputStream(new File(resDir + "META-INF"
				+ File.separator + "MANIFEST.MF")));
		// 声明输出jar流
		JarOutputStream out = new JarOutputStream(new BufferedOutputStream(fileOutputStream));

		for (int i = 0; i < fileList.size(); i++) {
			String fileName = fileList.get(i);
			fileName = fileName.replace(resDir, "");
			if (fileName.endsWith("MANIFEST.MF")) {
				continue;
			}
			InputStream in = new FileInputStream(fileList.get(i));

			JarEntry e = new JarEntry(fileName);
			e.setMethod(JarEntry.DEFLATED);
			out.putNextEntry(e);
			int len = 0;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
			out.closeEntry();
		}
		out.close();

	}

	private static List<String> list = null;

	private static List<String> listAllFile(String path) {
		File file = new File(path);
		String[] array = null;
		String sTemp = "";

		if (!file.isDirectory()) {
			return null;
		}
		array = file.list();
		if (array.length > 0) {
			for (int i = 0; i < array.length; i++) {
				sTemp = path + array[i];
				file = new File(sTemp);
				if (file.isDirectory()) {
					listAllFile(sTemp + "/");

				} else {
					list.add(sTemp);
				}
			}
		} else {
			return null;
		}

		return list;
	}
}
